<?php
declare (strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;
use app\common\model\Account as Accounts;
use app\common\model\Statistics as StatisticsModel;
use think\db\Where;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Event;

/**
 * @mixin \think\Model
 */
class Place extends Base
{

    protected $name = 'user_place';

    public function getAll($param)
    {
        try {

            return $this->where($param)->select()->toArray();

        } catch (\Exception $e) {
            return [];
        }
    }

    public function getCreateTimeAttr($value)
    {
        return date('Y-m-d', intval($value));
    }

    protected function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,code,nickname,mobile,level_id,position_total_1,position_total_2,position_total_3,is_active,position_total,market_num,my_total');
    }

    protected function fresh()
    {
        return $this->hasOne(User::class, 'id', 'new_uid')
            ->field('id,code,nickname,mobile,level_id,position_total_1,position_total_2,position_total_3,is_active,position_total,market_num,my_total');
    }


    /**
     * 原点 2020年8月22日16:25:27 记录推荐关系
     *
     * @param $uid -- 新会员ID
     * @param $code -- 新会员编号
     * @param $status -- 状态：默认0普通会员1正式会员
     * @param $parent_code -- 推荐人的编号
     * @return array
     */
    public function record($uid, $code, $place_id, $position)
    {
        try {
            $layers = 1;
            $time = time();
            $insert = [];
            $node_user_id = $place_id;
            while ($node_user = User::where('id', $node_user_id)->field('id,code,place_id,position')->find()) {
                if ($node_user) {
                    $data['uid'] = $node_user['id'];
                    $data['code'] = $node_user['code'];
                    $data['create_time'] = $time;
                    $data['new_uid'] = $uid;
                    $data['new_code'] = $code;
                    $data['layers'] = $layers;
                    $data['position'] = $position;
                    $insert[] = $data;
                    $node_user_id = $node_user['place_id'];
                    $position = $node_user['position'];
                }
                $layers++;
            }
            $this->insertAll($insert);
            return ['code' => 1, 'msg' => '操作成功'];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }


    public static function getPlace($parent_id,$place_id)
    {
        try {
                $parent = User::where(['parent_id'=>$parent_id])->find();//是否是第一个推荐的人
                if(!$parent)
                {
                    if($parent_id==$place_id)
                    {
                        $num =  Place::where(['uid'=>$parent_id,'layers'=>1])->count();
                        $parent_user =  User::where(['id'=>$parent_id])->find();
                        if($num+1 > $parent_user->market_num)
                        {
                            return ['code' => -1, 'msg' => '市场暂未开启，请选择其他安置人'];
                        }else{
                            return['code' => 1, 'position'=>$num+1];
                        }

                    }else{
                        $place_user = Place::where(['new_uid'=>$place_id,'uid'=>$parent_id,'position'=>1])->find();//安置人是否在推荐人第一市场
                        if(!$place_user)
                        {
                            return ['code' => -1, 'msg' => '安置人错误'];
                        }else{
                            $p_user = User::find($place_id);
                            $num = Place::where(['uid'=>$place_id,'layers'=>1])->count();//安置人第一层两个市场是否满了
                            if($p_user->market_num<$num+1)
                            {
                                return ['code' => -1, 'msg' => '位置错误，请更换安置人'];
                            }
                            switch ($num) {
                                case 0:
                                    return['code' => 1, 'position'=>1];
                                case 1:
                                    return['code' => 1, 'position'=>2];
                                default:
                                    return ['code' => -1, 'msg' => '安置人错误'];
                            }
                        }
                    }

                }else{
                    if($parent_id==$place_id)
                    {
                       $num =  Place::where(['uid'=>$parent_id,'layers'=>1])->count();
                       $parent_user =  User::where(['id'=>$parent_id])->find();
                       if($num+1 > $parent_user->market_num)
                       {
                           return ['code' => -1, 'msg' => '市场暂未开启，请选择其他安置人'];
                       }
                       return['code' => 1, 'position'=>$num+1];
                    }else{
                        $find = Place::where(['new_uid'=>$place_id,'uid'=>$parent_id])->find();
                        if($find)
                        {
                            $p_user = User::find($place_id);
                            $num = Place::where(['uid'=>$place_id,'layers'=>1])->count();//安置人第一层两个市场是否满了
                            if($p_user->market_num<$num+1)
                            {
                                return ['code' => -1, 'msg' => '位置错误，请更换安置人'];
                            }
                            switch ($num) {
                                case 0:
                                    return['code' => 1, 'position'=>1];
                                case 1:
                                    return['code' => 1, 'position'=>2];
                                default:
                                    return ['code' => -1, 'msg' => '安置人错误'];
                            }
                        }else{
                            return ['code' => -1, 'msg' => '安置人错误'];
                        }

                    }
                }

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function get_code($users)
    {
        try {
            foreach ($users as $k=>$v)
            {
                $count = User::where('place_id',$v->new_uid)->count();//查询下面安置人数量
                if($count)
                {
                    if($count<4)
                    {
//                         $user = User::where('place_id',$v->new_uid)->order('position','desc')->field('id,position,place_id')->find();//最后一个人

                         $list = User::where('place_id',$v->new_uid)->column('position');
                         $positions = array_diff(array(1,2,3,4),$list);
                         $user['position']=current($positions);
                         $user['place_id']=$v->new_uid;
                         return $user;
//                         dump($user->toArray());die;
                    }
                }else{
                    $user['place_id']=$v->new_uid;
                    $user['position']= 1 ;
                    return $user;
                }
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    //更新团队盒数
    public static function renewTeamNum($num, $uid, $key = 'team_num')
    {
        $all_id = parent::where('new_uid', $uid)->column('uid');
        if (!empty($all_id)) {
            User::whereIn('id', $all_id)->inc($key, floatval($num))->update();
        }
    }

    //更新团队盒数
    public static function renewTeamNums($num, $uid, $key = 'team_num')
    {
        $all_id = parent::where('new_uid', $uid)->column('uid');
        $all_id[] = $uid;
        if (!empty($all_id)) {
            User::whereIn('id', $all_id)->inc($key, floatval($num))->update();
        }
    }


    //升级
    public static function upgrade($uid)
    {
        try {
            $list = parent::with('user')->where('new_uid', $uid)
                ->field('id,uid,layers')->order('layers', 'asc')->select();//上级
            foreach ($list as $k=>$v)
            {
                $level = Level::where('id','>',$v->user->level_id)->order('id','asc')->find();//下一级
                if(isset($level))
                {

                    if($level->id==2)
                    {
                        $num = User::where(['place_id'=>$v->user->id,'is_active'=>2])->count();
                        if($num<2)
                        {
                            continue;
                        }
                    }

                    $referrals_num = 0;
                    if($level->referrals)
                    {
                        $referrals_num = User::where(['parent_id'=>$v->uid,'is_active'=>2])->count();//推荐人数
                    }

                    $market_num = 0;
                    if($level->market_num&&$level->position_total)
                    {
                       $num = range(1,$level->market_num);
                       foreach ($num as $key=>$value)
                       {
                         $position_total = 'position_total_'.$value;
                         if($v->user->$position_total>=$level->position_total)
                         {
                             $market_num++;
                         }
                       }

                    }
                    $num = 0;
                    if($level->superior&&$level->superior_num)
                    {
                        $p_level = $level->id-1;
                        $place = Place::where(['uid'=>$v->uid,'layers'=>1])->order('position','asc')->limit($level->superior_num)->select();
                        foreach ($place as $ke=>$va)
                        {
                            $all_id = parent::where('uid', $va->new_uid)
                                ->field('id,uid,layers')->order('layers', 'asc')->column('new_uid');//市场
                            $all_id[] =$va->new_uid;
                            if (!empty($all_id)) {
                                $is_num = User::whereIn('id', $all_id)->where('level_id','>=',$p_level)->count();
                                if($is_num)
                                {
                                    $num++;//伞下上个级别人数
                                }
                            }
                        }
                    }

                    if($level->referrals<=$referrals_num&&$level->market<=$v->user->market_num&&$level->market_num<=$market_num&&$level->superior_num<=$num)
                    {
                      User::where('id',$v->uid)->update(['level_id'=>$level->id]);
                      if($v->user->market_num<$level->openness)
                      {
                          User::where('id',$v->uid)->update(['market_num'=>$level->openness]);
                      }
                    }
                }

            }

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    public static function openness($uid)
    {
        $list = parent::with('user')->where('new_uid', $uid)
            ->field('id,uid,layers')->order('layers', 'asc')->select();//上级
        $openness = cache('system')['openness'];
        foreach ($list as $k=>$v)
        {
            $market_num = $v->user->market_num+1;
            $market = User::where(['position'=>$v->user->market_num,'place_id'=>$v->user->id])->find();
            if($market&&$market->position_total+$market->my_total>=$openness)
            {
                User::update(['market_num'=>$market_num],['id'=>$v->user->id]);
            }
        }

    }

    //自销奖励
    public static function purchase($uid){
        try {
            $user = User::where('id',$uid)->find();
            $level = Level::where('id',$user->level_id)->find();
            if($level->purchase&&$user->my_num>=$level->purchase)
            {
                if($level->purchase_creward)
                {
                    Account::getInstance()->basics($uid, 'bonus', $level->purchase_creward, '自销奖励', '自銷獎勵', '+')->createBonus($uid, 3);
                    Event::trigger('Statistics', ['key' => 'expend', 'value' => $level->purchase_creward]);
                }
                if($level->purchase_bonus)
                {
                    Account::getInstance()->basics($uid, 'capping', $level->purchase_bonus, '自销奖','自銷獎', '+')
                        ->createNormal($uid);
                }
            }
        } catch (\Exception $e) {
            dump($e->getMessage());die;
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    /**
     * @param $amount - 金额
     * @param $uid - 会员ID
     * @param string $key - 团队业绩key
     * 原点 2021年12月28日11:50:17 更新团队业绩
     */
    public static function renewTeamTotal($amount, $uid)
    {
        $list = array(1,2,3);
        foreach ($list as $k=>$v){
            $market = parent::where(['new_uid' => $uid, 'position' => $v])->column('uid');
            if (!empty($market)) {
                if($v==1)
                {
                    User::whereIn('id', $market)->inc('position_total_1', floatval($amount))->update();
                }
                if($v==2)
                {
                    User::whereIn('id', $market)->inc('position_total_2', floatval($amount))->update();
                }
                if($v==3)
                {
                    User::whereIn('id', $market)->inc('position_total_3', floatval($amount))->update();
                }
//                    $key = 'market_total'.$user->position;
            }
        }
        $markets = parent::where(['new_uid' => $uid])->column('uid');
        User::whereIn('id', $markets)->inc('position_total', floatval($amount))->update();

    }



    //平衡奖
    public static function colliding($uid)
    {
        try {
            $num = 0;
            $total = cache('system')['cardinal_number'];//对碰基数
            $colliding = cache('system')['colliding'];//对碰奖
            $list = parent::with('user')->where(['new_uid' => $uid])->field('id,uid,layers')->order('layers', 'asc')->select();//团队列表
            foreach ($list as $k => $v) {
                if (!$v->user->is_capping) {
                    $left_total = $v->user->left_total;
                    $right_total = $v->user->right_total;
                    //规定基数
                    $base = $total * 3;
                    $courtship = round($total * $colliding, 2);
                    //如果两区都小于基数，不碰
                    if ($left_total < $total || $right_total < $total) continue;
                    //判断大区
                    $max = $left_total > $right_total ? $left_total : $right_total;
                    //如果大区小于基数*3，不碰
                    if ($max < $base) continue;
                    $i = 0;
                    while ($max >= $base && $left_total > 0 && $right_total > 0) {
                        $i++;
                        if ($left_total > $right_total) {
                            $left_total -= $base;
                            $right_total -= $total;
                        } else {
                            $right_total -= $base;
                            $left_total -= $total;
                        }
                        $max = $left_total > $right_total ? $left_total : $right_total;
                    }

                    $real = $courtship * $i;
                    $update = [];
                    if ($real > 0) {
                        $courtships = $real + $v->user->release;
                        if ($courtships >= $v->user->capping) {
                            $real = $v->user->capping - $v->user->release;
                            $update['is_capping'] = 1;
//                            User::where('id', $v->user->id)->update(['is_capping' => 1]);
                        }
                        Accounts::reward($v->user->id, $real, '平衡奖', $uid, 5);
                        $num += $real;
                        $update['release'] = $v->user->release += floatval($real);
//                        User::where('id', $v->user->id)->inc('release', floatval($real))->update();//已释放增加
                    }
                    $update['left_total'] = $left_total;
                    $update['right_total'] = $right_total;
                    $update['id'] = $v->user->id;
                    User::update($update);

                }
            }
            StatisticsModel::_update($num, 'income');
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }



    //市场补贴
    public static function agent_award($uid)
    {
        try {
            $subsidy = Cache::get('system')['subsidy'];
            $examine = Cache::get('system')['examine'];//考核封顶
            $examine_performance = Cache::get('system')['examine_performance'];//考核业绩
            $user = User::find($uid);
            $num = 0;
            if ($user->place_id) {
                while ($user->place_id) {
                    $p_user = User::where(['id' => $user->place_id])->find();//查找安置人
                    if ($user->position<3) {//是否是小于3市场
                        $user = $p_user;//查找安置人
                    } else {
                        if($p_user->subsidy+$subsidy>$examine)
                        {
                             if($p_user->position_total_1>=$examine_performance&&$p_user->position_total_2>=$examine_performance)
                             {
                                 Target::Account()->basics($p_user->id, 'reward', $subsidy, '市场补贴', '+')
                                     ->createBonus($uid, 2);
                                 User::where('id', $p_user->id)->inc('subsidy', floatval($subsidy))->update();
                                 $p_user =  Assets::where(['uid'=>$p_user->id])->find();
                                 if($p_user->freeze)
                                 {
                                     $freeze =$p_user->freeze;
                                     $p_user->freeze = 0;
                                     $p_user->reward = $p_user->reward+$freeze;
                                     $p_user->save();
                                     $num+=$freeze;
                                 }
                                 $num+=$subsidy;
                             }else{
                                 if($p_user->subsidy>$examine)
                                 {
//                                     User::where('id', $uid)->inc('freeze_subsidy', floatval($subsidy))->update();
                                     Target::Account()->basics($p_user->id, 'freeze', $subsidy, '市场补贴', '+')
                                         ->createBonus($uid, 2);
                                 }else{
                                     $difference = $examine-$p_user->subsidy;
                                     Target::Account()->basics($p_user->id, 'reward', $difference, '市场补贴', '+')
                                         ->createBonus($uid, 2);
                                     $num+=$difference;

                                     User::where('id', $p_user->id)->inc('subsidy', floatval($subsidy))->update();
                                     $freeze_subsidy =  $subsidy-$difference;
//                                     User::where('id', $uid)->inc('freeze_subsidy', floatval($freeze_subsidy))->update();
                                     Target::Account()->basics($p_user->id, 'freeze', $freeze_subsidy, '市场补贴', '+')
                                         ->createBonus($uid, 2);
                                 }
                             }
                        }else{
                            Target::Account()->basics($p_user->id, 'reward', $subsidy, '市场补贴', '+')
                                ->createBonus($uid, 2);
                            User::where('id', $p_user->id)->inc('subsidy', floatval($subsidy))->update();
                            $num+=$subsidy;
                        }

                        break;
                    }
                }
                Event::trigger('Statistics', ['key' => 'expend', 'value' => $num]);
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }


    //管理补贴
    public static function manage_subsidy($uid)
    {
        try {
                $list = parent::where(['new_uid' => $uid])->order('layers', 'asc')->column('uid');
                array_unshift($list,$uid);
                $level_id = 0;
                $level_manage = 0;
                foreach ($list as $k=>$v)
                {
                    $user = User::find($v);
                    if($user->place_id)
                    {
                        $p_user = User::find($user->place_id);
                        if($p_user->place_id)
                        {
                            $pp_user = User::find($p_user->place_id);

                            if($user->position<3)
                            {
                                if($pp_user->level_id>$level_id)
                                {
                                    $level = Level::find($pp_user->level_id);
                                    $manage = $level->manage-$level_manage;
                                    if($manage>0)
                                    {
                                        Target::Account()->basics($pp_user->id, 'reward', $manage, '管理补贴', '+')
                                            ->createBonus($uid, 3);
                                        Event::trigger('Statistics', ['key' => 'expend', 'value' => $manage]);

                                        $ppp_user = User::find($pp_user->place_id);
                                        if($pp_user->level_id==$ppp_user->level_id){
                                            $manage_level = Cache::get('system')['manage_level'];
                                            Target::Account()->basics($ppp_user->id, 'reward', $manage_level, '管理平级', '+')
                                                ->createBonus($pp_user->id, 4);
                                            Event::trigger('Statistics', ['key' => 'expend', 'value' => $manage_level]);
                                        }
                                    }

                                    $level_id = $pp_user->level_id;
                                    $level_manage = $level->manage;
                                }


                            }else{
                                break;
                            }
                        }else{
                            break;
                        }
                    }

                }

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }


    //复消补贴
    public static function recoil_subsidy($uid)
    {
        try {
            $list = parent::where(['new_uid' => $uid])->order('layers', 'asc')->column('uid');
            array_unshift($list,$uid);
            $level_id = 0;
            $level_recoil = 0;
            foreach ($list as $k=>$v)
            {
                $user = User::find($v);
                if($user->place_id)
                {
                    $p_user = User::find($user->place_id);
                    if($p_user->place_id)
                    {
                        $pp_user = User::find($p_user->place_id);

                        if($user->position<3)
                        {
                            if($pp_user->level_id>$level_id)
                            {
                                $level = Level::find($pp_user->level_id);
                                if($level->id==1)
                                {
                                    if($p_user->position<3)
                                    {
                                        continue;
                                    }
                                }
                                $recoil = $level->recoil-$level_recoil;
                                if($recoil>0)
                                {
                                    Target::Account()->basics($pp_user->id, 'reward', $recoil, '复消补贴', '+')
                                        ->createBonus($uid, 5);
                                    Event::trigger('Statistics', ['key' => 'expend', 'value' => $recoil]);

                                    $ppp_user = User::find($pp_user->place_id);
                                    if($pp_user->level_id==$ppp_user->level_id){
                                        $recoil_level = Cache::get('system')['recoil_level'];
                                        Target::Account()->basics($ppp_user->id, 'reward', $recoil_level, '复消平级', '+')
                                            ->createBonus($pp_user->id, 6);
                                        Event::trigger('Statistics', ['key' => 'expend', 'value' => $recoil_level]);
                                    }
                                }

                                $level_id = $pp_user->level_id;
                                $level_recoil = $level->recoil;
                            }

                        }else{
                            break;
                        }
                    }else{
                        break;
                    }
                }

            }

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }


    /**
     * @param $uid
     * @param $total
     * @return array
     * 原点 2022年11月8日16:03:51 更新层级业绩
     */
    public static function renewLayerTotal($uid, $total): array
    {
        try {
            Db::execute('update `user_place` set left_total = left_total + ' . $total . ' , left_surplus = left_surplus + ' . $total . ' where new_uid = ' . $uid . ' and position = 1');
            Db::execute('update `user_place` set right_total = right_total + ' . $total . ' , right_surplus = right_surplus + ' . $total . ' where new_uid = ' . $uid . ' and position = 2');
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

//    /**
//     * @param $uid
//     * @return array
//     * 原点 2022年11月8日16:20:27 对碰奖
//     */
//    public static function colliding($uid): array
//    {
//        try {
//            $list = parent::where('new_uid', $uid)->order('layers', 'asc')->select();
//            $expendTotal = 0;
//            foreach ($list as $item) {
//                //如果在左区
//                if ($item->position == 1) {
////                    echo 1;die;
//                    //查询右区结余
//                    $right = PlaceSurplus::where(['uid' => $item->uid])->find();
//                    if (empty($right)) {
//                        continue;
//                    }
//
//                    if ($right->left_surplus <= 0 || $right->right_surplus <= 0) {
//                        continue;
//                    }
//                    //选出比较小的一方
//                    $total = $right->left_surplus > $right->right_surplus ? $right->right_surplus : $right->left_surplus;
//                    //去掉碰撞的结余
//                    $right->left_surplus = $right->left_surplus - $total;
//                    $right->save();
//
//                    $right->right_surplus = $right->right_surplus - $total;
//                    $right->save();
//                } else {
//
//                    $left = PlaceSurplus::where(['uid' => $item->uid])->find();
//                    if (empty($left)) {
//                        continue;
//                    }
//                    //查询左区结余
//                    if ($left->right_surplus <= 0 || $left->left_surplus <= 0) {
//                        continue;
//                    }
//
//                    //选出比较小的一方
//                    $total = $left->right_surplus > $left->left_surplus ? $left->left_surplus : $left->right_surplus;
//                    //去掉碰撞的结余
//                    $left->right_surplus = $left->right_surplus - $total;
//                    $left->save();
//
//                    $left->left_surplus = $left->left_surplus - $total;
//                    $left->save();
//                }
//
//
//                $users = User::where('id',$item->uid)->field('id,level_id,yj_capping,yj_release,is_yj_release')->find();//安置人
//
//                if(!$users->is_yj_release)//是否封顶
//                {
//                    $level = Level::where('id',$users->level_id)->find();//等级
//
//                    $cashs = bcmul((string)$total,(string)$level->achievement,2);//奖励
//                    if($users->yj_release+$cashs>$users->yj_capping)
//                    {
//                        $cashs = $users->yj_capping-$users->yj_release;
//                    }
//                    if($cashs)
//                    {
//                        $double_spending = cache('system')['double_spending'];
//                        $amount = bcmul((string)$cashs,(string)$double_spending,2);
//                        $sum = $cashs-$amount;
//                        Account::getInstance()->basics($users->id, 'bonus', $sum, '业绩奖','業績獎', '+')->createBonus($item->uid, 4);
//                        Account::getInstance()->basics($users->id, 'points', $amount, '重复消费','重複消費', '+')
//                            ->createNormal($users->id);
//                        User::where('id', $users->id)->inc('yj_release', (float)$cashs)->update();
//                        $expendTotal += $cashs;
//                        //管理奖
//                        $res = Relation::officer($item->uid, $cashs);
//                    }else{
//                        User::update(['is_yj_release'=>1],['id'=>$users->id]);
//                    }
//                }
//            }
//            if ($expendTotal > 0) {
//                Event::trigger('Statistics', ['key' => 'expend', 'value' => $expendTotal]);
//            }
//            return ['code' => 1, 'msg' => 'success'];
//        } catch (\Exception $e) {
//            dump($e->getMessage());die;
//            return ['code' => -1, 'msg' => $e->getMessage()];
//        }
//    }


}
